package me.zhengjie.minbearwcs.listener.inbound;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.minbearwcs.dao.inbound.inf.InboundOrderDao;
import me.zhengjie.minbearwcs.entity.DTO.inbound.wcs.InboundMissionFactor;
import me.zhengjie.minbearwcs.entity.PO.wcs.inbound.status.InboundOrderStatus;
import me.zhengjie.minbearwcs.utils.LogFileKey;
import me.zhengjie.observer.event.IWcsEvent;
import me.zhengjie.observer.listener.IWcsEventListener;
import me.zhengjie.observer.type.WcsEventType;
import me.zhengjie.observer.type.inbound.InboundEventType;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


/**
 * 更新工单状态
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class InboundOrderStartListener implements IWcsEventListener {

    private final InboundOrderDao inboundOrderDao;
    private final Object lock = new Object();

    @Override
    @Transactional
    public void onEvent(IWcsEvent wcsEvent) {
        MDC.put(LogFileKey.KEY, LogFileKey.Module.INBOUND);
        InboundMissionFactor missionSource = (InboundMissionFactor) wcsEvent.getSource();
        String inboundOrderCode = missionSource.getInboundOrderCode();

        // 更新工单状态
        if (InboundOrderStatus.READY == inboundOrderDao.selectStatusByInboundOrderCode(inboundOrderCode)) {
            synchronized (lock) {
                if (InboundOrderStatus.READY == inboundOrderDao.selectStatusByInboundOrderCode(inboundOrderCode)) {
                    inboundOrderDao.updateStatusByInboundOrderCode(inboundOrderCode, InboundOrderStatus.PROCESSING);
                    inboundOrderDao.updateStartTimeByInboundOrderCode(inboundOrderCode, LocalDateTime.now());
                    log.info("出库单 {} ，开始执行", inboundOrderCode);
                }
            }
        }
        MDC.remove(LogFileKey.KEY);
    }

    @Override
    public WcsEventType getEventType() {
        return InboundEventType.INBOUND_CALL_AGV;
    }
}
